package org.third.common.datasource;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.third.common.domain.Deployment;
import org.third.common.domain.entity.DeploymentStatus;
import org.third.common.utils.StringUtils;
import org.third.suite.service.InstallerDataSourceService;

import com.esotericsoftware.yamlbeans.YamlReader;

/**
 * Created by Huailong Tang(Jason) on 2017/10/18.
 */
@Component
@Order(value = 2)
public class InstallerDataSourceInit implements CommandLineRunner {

	@Autowired
	private InstallerDataSourceService installerDataSourceService;


	@Autowired
	private Environment springEnv;

	private static final Logger logger = LoggerFactory.getLogger(InstallerDataSourceInit.class);

	@Override
	public void run(String... strings) throws Exception {
		if (installerDataSourceService.databaseExistInKube()) {
			if (installerDataSourceService.databaseReadyWithRetry()) {
				logger.info("Postgres already startup ...");
				installerDataSourceService.addNewDataSourceAtRuntime();
				installerDataSourceService.initialize();
				convertTo09();
			} else {
				throw new RuntimeException("Can't connect to postgres ,maybe postgres has crashed ...");
			}
		} else {
			logger.error("postgres not ready");
		}
	}

	@Transactional
	private void convertTo09() {

//		Iterable<Deployment> deploymentIterral = deploymentRepository.findAll();
//		Iterator<Deployment> depIterator = deploymentIterral.iterator();
//		while (depIterator.hasNext()) {
//			Deployment nextDep = depIterator.next();
//			if (null != nextDep.getFeature() && !StringUtils.isEmpty(nextDep.getFeature().getFeature())) {
//				try {
//					// delete suit configpdo
//					// if(null !=nextDep.getSuiteConfigurationPod()&&){
//					// logger.info("delete suite config pod suite name: "
//					// +nextDep.getSuiteConfigurationPod().getSuite());
//					// suiteConfYamlRuntimeBO.deleteSuiteConfPod(nextDep.getSuiteConfigurationPod().getSuite());
//					// }
//					logger.info("nextDep.getStatus().equals(DeploymentStatus.INSTALL_FINISHED)"
//							+ (nextDep.getStatus().equals(DeploymentStatus.INSTALL_FINISHED)));
//					logger.info("nextDep.getStatus()==DeploymentStatus.INSTALL_FINISHED"
//							+ (nextDep.getStatus() == DeploymentStatus.INSTALL_FINISHED));
//					if (nextDep.getStatus() == DeploymentStatus.INSTALL_FINISHED) {
//						String version = nextDep.getSuiteConfigurationPod().getSuiteVersion();
//						String nameSpace = nextDep.getSuiteConfigurationPod().getNamespace();
//						String labelKey = nextDep.getSuiteConfigurationPod().getLabelKey();
//						String labelValue = nextDep.getSuiteConfigurationPod().getLabelValue();
//						String suite = nextDep.getSuiteConfigurationPod().getSuite();
//						// NEED TO CREATE TMP
//						kubesQueryRegistryImageService.genSuiteConfig(suite);
//						// from nfs to get thing
//						logger.info("version  : " + version + "  nameSpace : " + nameSpace + " labelKey : " + labelKey
//								+ " suite : " + suite + " labelValue : " + labelValue);
//						String newPath = springEnv.getRequiredProperty("ss.container.pv.folder") + "/" + suite + "/"
//								+ springEnv.getRequiredProperty("ss.configuration.suite-conf-yaml-file.name");
//						File nfsPath = new File(newPath);
//						logger.info(">>>>>>> nfsPath.exists()" + nfsPath.exists());
//						if (nfsPath.exists()) {
//							Map<String, String> map = new HashMap<>();
//							map = getParamsFromNfs(nfsPath);
//							logger.info(">>>>>>> map.isEmpty()" + map.isEmpty());
//
//							logger.info(">>>>>>> map.get(\"EULA\")" + map.get("EULA"));
//
//							logger.info(">>>>>>> map.get(\"instanceId\")" + map.get("instanceId"));
//							logger.info(">>>>>>> map.get(\"CALL_HOME\")" + map.get("CALL_HOME"));
//
//							if (!map.isEmpty()) {
//								int instance = Integer.parseInt(map.get("instanceId"));
//								suiteConfYamlRuntimeBO.genSuiteConfYaml(nextDep.getUuid(), suite, version, nameSpace,
//										labelKey, labelValue, map.get("EULA"), map.get("CALL_HOME"), instance);
//								// need to do
//								// suiteConfYamlRuntimeBO.createSuiteConfPod(content);
//							}
//						}
//					}
//					String transFormedFeature = JsonNodeUtil.suiteFeatureConvertTo09(nextDep.getFeature().getFeature());
//					nextDep.getFeature().setFeature(transFormedFeature);
//					deploymentRepository.save(nextDep);
//				} catch (Exception E) {
//					logger.error("conver all  suitefeaturejson to 09version has exception  {}", E.getMessage());
//				}
//			}
//		}

	}

	public Map<String, String> getParamsFromNfs(File nfsPathFile) throws Exception {

		Map<String, String> myMap = new HashMap<>();
		List<String> yamlContentList = new ArrayList<>();
		InputStream is = new FileInputStream(nfsPathFile);
		yamlContentList = StringUtils.splitYamlByDash(is);
		for (String yamlContent : yamlContentList) {
			YamlReader yamlReader = new YamlReader(new StringReader(yamlContent));
			Map map = null;
			map = (Map) yamlReader.read();
			logger.info(">>>>kind " + (String) map.get("kind"));
			if ("ConfigMap".equalsIgnoreCase((String) map.get("kind"))) {
				String instanceId = (String) ((Map) map.get("data")).get("suite.namespace.id");
				String EULA = (String) ((Map) map.get("data")).get("EULA");
				String CALL_HOME = (String) ((Map) map.get("data")).get("CALL_HOME");
				logger.info("EULA  : " + EULA + "  CALL_HOME : " + CALL_HOME + " instanceId : " + instanceId);
				myMap.put("instanceId", instanceId);

				myMap.put("EULA", EULA);
				myMap.put("CALL_HOME", CALL_HOME);

			}
			is.close();

		}

		return myMap;

	}
}
